var vertexShader = 
`
attribute vec2 a_position;
attribute vec2 a_texCoord;
varying mediump vec2 v_texCoord;
void main()
{
    // gl_Position = (MVP) * a_position;
    gl_Position = vec4(a_position, 0, 1);
    v_texCoord = a_texCoord;
}
`;
var fragmentShader = 
`
precision lowp float;
varying vec2 v_texCoord;
uniform float u_alpha;
uniform sampler2D u_Sample;
void main()
{
    // gl_FragColor = vec4(v_texCoord, 0, 1);
    vec4 color = texture2D(u_Sample, v_texCoord);
    color.a *= u_alpha;
    float alpha = color.a;
    if(color.a < 0.3)
    {
        alpha = 0.0;
        color.rgb = vec3(0.0, 0.0, 0.0);
    }
    color.a = alpha;
    gl_FragColor = color;
    // gl_FragColor = vec4(1, 0, 0, 1);
}
`;

var vertexShader_texture = 
`
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform vec2 u_offset;
varying mediump vec2 v_texCoord;
void main()
{
    // gl_Position = (MVP) * a_position;
    gl_Position = vec4(a_position + u_offset, 0, 1);
    v_texCoord = a_texCoord;
}
`;
var fragmentShader_texture = 
`
precision lowp float;
varying vec2 v_texCoord;
uniform sampler2D u_Sample;
void main()
{
    // gl_FragColor = vec4(v_texCoord, 0, 1);
    gl_FragColor = texture2D(u_Sample, v_texCoord);
    // gl_FragColor = vec4(1, 0, 0, 1);
}
`;

function main()
{
    canvas = document.getElementById("canvas");
    gl = canvas.getContext("experimental-webgl");
    if(!gl)
    {
        console.log("your browers not support webgl");
        return;
    } 

    program = createGLProgram(vertexShader, fragmentShader);
    texProgram = createGLProgram(vertexShader_texture, fragmentShader_texture);
    createFrameBuffer();
    createFrameBuffer2();

    var img = new Image();
    
    img.src = "http://localhost/img.png";
    img.crossOrigin = "";
    img.onload = function()
    {
        offsetX = 0.0;
        offsetY = 0.0;
    
        var i = 0;
        setInterval(function() {
            //  if(i>10)
            //  return;
            offsetX = 0.2 * Math.sin(i / 10);
            offsetY = 0.5 * Math.sin(i / 20);
            
            
                start();
                drawRole(img);
                end();
            
                drawRole(img);    
            
            
            setBufferAlpha(1);
            drawScene();
            setBufferAlpha2(0.99);
            i++;
        }, "16");


/*
offsetX = -0.5;        
start();
drawRole(img);
end();
setBufferAlpha(1);
drawScene();

setBufferAlpha2(1);
offsetX = 0.3;
start();
drawRole(img);
end();
setBufferAlpha(1);
drawScene();
setBufferAlpha2(1);
*/

// offsetX = 0.1;
// offsetY = 0.1;
// start();
// drawRole(img);
// end();
// setBufferAlpha(1);
// drawScene();





        // for(var i=0; i<12; i++)
        // {
        //     offsetX = i / 20.0;
        //     offsetY = i / 20.0;
        //     // drawGhost();
        //     start();
        //     drawRole(img);
        //     end();
        //     setBufferAlpha(1);
        //     drawScene(); 
        //     setBufferAlpha2(0.9)
        //     i++;
        // }

    }




}


function createFrameBuffer()
{
    var width = canvas.width;
    var height = canvas.height;
    offScreenTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, offScreenTexture);

    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);    //声明offscreenTex的空间
    gl.bindTexture(gl.TEXTURE_2D, null);
    fbo = gl.createFramebuffer();

}

function createFrameBuffer2()
{
    var width = canvas.width;
    var height = canvas.height;
    offScreenTexture2 = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, offScreenTexture2);

    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);    //声明offscreenTex的空间
    gl.bindTexture(gl.TEXTURE_2D, null);
    fbo2 = gl.createFramebuffer();

}

function start()
{
    
    gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);    //绑定Framebuffer
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, offScreenTexture, 0);  //绑定纹理
}

function start2()
{
    gl.bindFramebuffer(gl.FRAMEBUFFER, fbo2);    //绑定Framebuffer
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, offScreenTexture2, 0);  //绑定纹理
}

function end()
{
    
    gl.bindTexture(gl.TEXTURE_2D, null);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}

function end2()
{
    
    gl.bindTexture(gl.TEXTURE_2D, null);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}

//fbo1 -> fbo2 清除fbo2中缓存
function setBufferAlpha(val)
{
    start2();
    // gl.clearColor(0, 0, 0, 0);//设置clearColor
    // gl.clear(gl.COLOR_BUFFER_BIT);     //clear
    gl.clearColor(1, 1, 1, 1);//设置clearColor
    gl.clear(gl.COLOR_BUFFER_BIT);     //clear
    var scale2 = 1.0;
    gl.useProgram(program);
    var posBuffer2 = gl.createBuffer();

    var vertices = new Float32Array([
        // -0.5, -1.0,
        //  1.0, -1.0,
        // -0.5,  1.0,
        // -0.5,  1.0,
        //  1.0, -1.0,
        //  1.0,  1.0

        // -1, -1.0, 0, 0,
        //  1, -1.0, 1, 0,
        // -1,  1.0, 0, 1,
        //  1,  1.0, 1, 1, 

       -1 * scale2, -1.0 * scale2,     0, 0,
        1 * scale2, -1.0 * scale2,     1, 0,
       -1 * scale2,  1.0 * scale2,     0, 1,
        1 * scale2,  1.0 * scale2,     1, 1,
          
        
        ]);

    var FSIZE = vertices.BYTES_PER_ELEMENT;
    gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer2);
    gl.bufferData(gl.ARRAY_BUFFER, vertices,
      gl.STATIC_DRAW);

    var positionLocation = gl.getAttribLocation(program, "a_position");
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, FSIZE * 4, 0);

    var a_texCoord = gl.getAttribLocation(program, 'a_texCoord');
    gl.enableVertexAttribArray(a_texCoord);
    gl.vertexAttribPointer(a_texCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2);
    
    // var u_Sampler = gl.getUniformLocation(program, 'u_Sampler');
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, offScreenTexture);
    // gl.uniform1i(u_Sampler, 0);
    
    var u_alpha = gl.getUniformLocation(program, 'u_alpha');
    gl.uniform1f(u_alpha, val);

  
    // var primitiveType = gl.TRIANGLES;
    var primitiveType = gl.TRIANGLE_STRIP;
    var offset = 0;
    // var count = 6;
    var count = 4;


    gl.drawArrays(primitiveType, offset, count);
    // gl.deleteBuffer(posBuffer2);
    // console.log("draw end!");
    end2();
}

//fbo2 -> fbo1 要清除缓存
function setBufferAlpha2(val)
{
    start();
    gl.clearColor(1, 1, 1, 1);//设置clearColor
    gl.clear(gl.COLOR_BUFFER_BIT);     //clear
    var scale3 = 1.0;
    gl.useProgram(program);
    var posBuffer3 = gl.createBuffer();

    var vertices = new Float32Array([
        // -0.5, -1.0,
        //  1.0, -1.0,
        // -0.5,  1.0,
        // -0.5,  1.0,
        //  1.0, -1.0,
        //  1.0,  1.0

        // -1, -1.0, 0, 0,
        //  1, -1.0, 1, 0,
        // -1,  1.0, 0, 1,
        //  1,  1.0, 1, 1, 

       -1 * scale3, -1.0 * scale3,     0, 0,
        1 * scale3, -1.0 * scale3,     1, 0,
       -1 * scale3,  1.0 * scale3,     0, 1,
        1 * scale3,  1.0 * scale3,     1, 1,
          
        
        ]);

    var FSIZE = vertices.BYTES_PER_ELEMENT;
    gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer3);
    gl.bufferData(gl.ARRAY_BUFFER, vertices,
      gl.STATIC_DRAW);

    var positionLocation = gl.getAttribLocation(program, "a_position");
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, FSIZE * 4, 0);

    var a_texCoord = gl.getAttribLocation(program, 'a_texCoord');
    gl.enableVertexAttribArray(a_texCoord);
    gl.vertexAttribPointer(a_texCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2);
    
    // var u_Sampler = gl.getUniformLocation(program, 'u_Sampler');
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, offScreenTexture2);
    // gl.uniform1i(u_Sampler, 0);
    
    var u_alpha = gl.getUniformLocation(program, 'u_alpha');
    gl.uniform1f(u_alpha, val);

    
    // var primitiveType = gl.TRIANGLES;
    var primitiveType = gl.TRIANGLE_STRIP;
    var offset = 0;
    // var count = 6;
    var count = 4;

    gl.drawArrays(primitiveType, offset, count);
    // gl.deleteBuffer(posBuffer3);
    // console.log("draw end!");
    end();
}

/**
 * 
 * @param {*vertShader string} vertexShaderSource 
 * @param {*fragShader string} fragmentShaderSource 
 */
function createGLProgram(vertexShaderSource, fragmentShaderSource)
{
    var resultProgram = gl.createProgram();
    var resVs = createShaderByType(vertexShaderSource, gl.VERTEX_SHADER);
    var resFs = createShaderByType(fragmentShaderSource, gl.FRAGMENT_SHADER);
    gl.attachShader(resultProgram, resVs);
    gl.attachShader(resultProgram, resFs);
    gl.linkProgram(resultProgram);
    if(!gl.getProgramParameter(resultProgram, gl.LINK_STATUS))
    {
        // var info = gl.getProgramParameter(resultProgram);
        throw new Error('Could not compile WebGL program.' /*+ info*/);
    }
    return resultProgram;
}

function createShaderByType(shaderSource, shaderType)
{
    var shader = gl.createShader(shaderType);
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) 
    {
        console.error(gl.getShaderInfoLog(shader));
    }
    return shader;
}
function drawRole(img)
{
    // document.body.appendChild(img);
    gl.useProgram(texProgram);
    var scale = 0.3;
    var vertices =  new Float32Array([

        -1 * scale, -1.0 * scale,     0, 0,
         1 * scale, -1.0 * scale,     1, 0,
        -1 * scale,  1.0 * scale,     0, 1,
         1 * scale,  1.0 * scale,     1, 1,
        
          
        
        ]);
    var posBuffer1 = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer1);
    gl.bufferData(gl.ARRAY_BUFFER,
        vertices,
        gl.STATIC_DRAW);

    var FSIZE = vertices.BYTES_PER_ELEMENT;
    
    var positionLocation = gl.getAttribLocation(texProgram, "a_position");
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, FSIZE * 4, 0);

    var a_texCoord = gl.getAttribLocation(texProgram, 'a_texCoord');
    gl.vertexAttribPointer(a_texCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2);
    gl.enableVertexAttribArray(a_texCoord);
    
    u_offset = gl.getUniformLocation(texProgram, 'u_offset');
    gl.uniform2f(u_offset, offsetX, offsetY);


    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);   //读入的图片为颠倒的 需要上下翻转下
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
    

    // var u_Sampler = gl.getUniformLocation(texProgram, 'u_Sampler');
    gl.activeTexture(gl.TEXTURE0);
    // gl.uniform1i(u_Sampler, 0);
    
    // var primitiveType = gl.TRIANGLES;
    var primitiveType = gl.TRIANGLE_STRIP;
    var offset = 0;
    // var count = 6;
    var count = 4;
    
    gl.enable(gl.BLEND);//开启混合
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);//设置混合模式

    
    gl.drawArrays(primitiveType, offset, count);
    gl.deleteBuffer(posBuffer1);
    

}
function drawScene()
{
    var scale2 = 1.0;
    gl.useProgram(program);
    var posBuffer4 = gl.createBuffer();

    var vertices = new Float32Array([
        // -0.5, -1.0,
        //  1.0, -1.0,
        // -0.5,  1.0,
        // -0.5,  1.0,
        //  1.0, -1.0,
        //  1.0,  1.0

        // -1, -1.0, 0, 0,
        //  1, -1.0, 1, 0,
        // -1,  1.0, 0, 1,
        //  1,  1.0, 1, 1, 

       -1 * scale2, -1.0 * scale2,     0, 0,
        1 * scale2, -1.0 * scale2,     1, 0,
       -1 * scale2,  1.0 * scale2,     0, 1,
        1 * scale2,  1.0 * scale2,     1, 1,
          
        
        ]);

    var FSIZE = vertices.BYTES_PER_ELEMENT;
    
    var positionLocation = gl.getAttribLocation(program, "a_position");
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, FSIZE * 4, 0);

    var a_texCoord = gl.getAttribLocation(program, 'a_texCoord');
    gl.vertexAttribPointer(a_texCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2);
    gl.enableVertexAttribArray(a_texCoord);
    
    // var u_Sampler = gl.getUniformLocation(program, 'u_Sampler');
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, offScreenTexture2);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    // gl.uniform1i(u_Sampler, 0);
    
    var u_alpha = gl.getUniformLocation(program, 'u_alpha');
    gl.uniform1f(u_alpha, 1);

    gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer4);
    gl.bufferData(gl.ARRAY_BUFFER, vertices,
      gl.STATIC_DRAW);
    // var primitiveType = gl.TRIANGLES;
    var primitiveType = gl.TRIANGLE_STRIP;
    var offset = 0;
    // var count = 6;
    var count = 4;

    gl.clearColor(0, 0.0, 0, 1);//设置clearColor
    gl.clear(gl.COLOR_BUFFER_BIT| gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);     //clear
    
    gl.drawArrays(primitiveType, offset, count);
    // gl.deleteBuffer(posBuffer4);
    // console.log("draw end!");

}

main();